<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btnList="fullInfo.btnList"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="setRules()"
              :label-width="formInfo.labelWidth"
              :list-type-info="listTypeInfo"
            >
              <template v-slot:form-patrolRouteName>
                <el-input
                  v-model="formInfo.data.patrolRouteName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择巡检路线"
                >
                  <template #append>
                    <el-icon @click="selectPatrolRoute"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-assetName>
                <el-input
                  v-model="formInfo.data.assetName"
                  class="not-mongolia"
                  type="input"
                  :required="true"
                  :disabled="true"
                  placeholder="请选择资产"
                >
                  <template #append>
                    <el-icon @click="selectAsset"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('detailInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <new-page-filter
              v-model:query="filterInfo.query"
              :filter-btn="filterInfo.list"
            >
              <template v-slot:filter-addItem>
                <el-button :disabled="!canAddItem" @click="addItem"
                  >添加项目</el-button
                >
              </template>
              <template v-slot:filter-removeItem>
                <el-button :disabled="!canRemoveItem" @click="removeItem()"
                  >删除项目</el-button
                >
              </template>
            </new-page-filter>
            <div class="flex_full_item">
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :tabIndex="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <SelectPatrolItem
      v-if="selectPatrolItemInfo.visible"
      v-model:showDialog="selectPatrolItemInfo.visible"
      :excludeQueryList="selectPatrolItemInfo.excludeQueryList"
      :query="selectPatrolItemInfo.query.queryMap"
      :check-box="true"
      @callback="selectPatrolItemCallBack"
    />
    <SelectPatrolRoute
      v-if="selectPatrolRouteInfo.visible"
      v-model:showDialog="selectPatrolRouteInfo.visible"
      :excludeQueryList="selectPatrolRouteInfo.excludeQueryList"
      :query="selectPatrolRouteInfo.query"
      :check-box="false"
      :highlight-row="true"
      @callback="selectPatrolRouteCallBack"
    />
    <!-- 选择资产 -->
    <SelectAsset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :highlight-row="true"
      :check-box="false"
      :save-empty="true"
      row-key="id"
      :table-key="selectAssetInfo.tableKey"
      :api="selectAssetInfo.api"
      @callback="callbackAsset"
    />
  </div>
</template>

<script setup name="patrolAreaModify">
import {
  createPatrolArea,
  getPatrolAreaById,
  updatePatrolArea,
  assetCustomizeListPage,
} from '@/api/core'
import { getCustomizeSetting } from '@/api/customize'
import { getPatrolItemCustomizeListPage } from '@/api/core'
const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'title', 'id', 'type'])

const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
// 表单相关
const formInfo = ref({
  ref: null,
  data: {
    assetName: '',
    assetId: '',
    patrolRouteName: '',
    patrolRouteId: '',
    patrolAreaType: 0,
  },
  fieldList: [
    {
      label: '名称',
      value: 'areaName',
      type: 'input',
      maxlength: 32,
    },
    {
      label: '巡检路线',
      value: 'patrolRouteName',
      type: 'slot',
    },
    {
      label: '类型',
      value: 'patrolAreaType',
      type: 'radio-model',
      code: 'patrol_area_type',
    },
    {
      label: '资产',
      value: 'assetName',
      type: 'slot',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '位置',
      value: 'location',
      type: 'input',
    },
    {
      label: '巡检说明',
      value: 'inspectionDesc',
      type: 'textarea',
    },
  ],
  noAssetRules: {
    areaName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    patrolRouteName: [
      { required: true, message: '请输入巡检路线', trigger: 'change' },
    ],
    patrolAreaType: [
      { required: true, message: '请输入类型', trigger: 'blur' },
    ],
  },
  assetRules: {
    areaName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    assetName: [{ required: true, message: '请选择资产', trigger: 'change' }],
    patrolRouteName: [
      { required: true, message: '请选择巡检路线', trigger: 'change' },
    ],
    patrolAreaType: [
      { required: true, message: '请输入类型', trigger: 'blur' },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      id: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', value: 'addItem' },
    { type: 'slot', value: 'removeItem' },
  ],
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  map: new Map(),
  isSysGroup: true, //新增修改页是否有后端合并
  sysGroup: [], //新增修改页后端合并项
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeItem,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
const selectPatrolItemInfo = ref({
  visible: false,
  excludeQueryList: [],
  query: {
    customizeUserVO: {},
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
})
const selectPatrolRouteInfo = ref({
  visible: false,
  excludeQueryList: [],
  query: {
    customizeUserVO: {},
    queryMap: {},
    queryParams: {},
  },
})
const selectAssetInfo = ref({
  visible: false,
  api: assetCustomizeListPage,
  tableKey:
    'assetAssetManagePatrolAddAsset-com.slip.spd.entity.vo.core.CoreAssetVO',
  query: {
    queryMap: {
      useDeptId: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
      manageDeptId: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
      deviceType: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      isMaintenance: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      assetSourceAuth: {
        asTbName: 'core_asset,core_asset',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },

    },
    queryParams: {
      patrolAreaId: props.id,
      // isInUseAsset:1,
    },
  },
})
// 相关列表
const listTypeInfo = ref({})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canAddItem = computed(() => {
  return formInfo.value.data.areaName && formInfo.value.data.areaName
})
const canRemoveItem = computed(() => {
  return tableInfo.value.selections.length
})

watch(
  () => formInfo.value.data.patrolAreaType,
  (value) => {
    if (value == '1') {
      formInfo.value.data['assetId'] = ''
      formInfo.value.data['assetName'] = ''
      formInfo.value.data['assetCode'] = ''
      formInfo.value.data['location'] = ''
      showFieldListItem(false, 'assetName')
      disableFieldListItem(false, 'location')
    } else {
      showFieldListItem(true, 'assetName')
      disableFieldListItem(true, 'location')
    }
    setRules()
  }
)

setData()
function setData() {
  let obj = {
    itemName: {
      label: '名称',
      value: 'itemName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function setRules() {
  proxy.$nextTick(() => {
    formInfo.value.ref.clearValidate()
  })
  const patrolAreaType = formInfo.value.data.patrolAreaType
  if (patrolAreaType == '1') {
    return formInfo.value.noAssetRules
  } else {
    return formInfo.value.assetRules
  }
}
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}
//选择入库仓库
function selectPatrolRoute() {
  selectPatrolRouteInfo.value.visible = true
}
function selectAsset() {
  selectAssetInfo.value.visible = true
}
function removeItem(selectRow = undefined) {
  if (selectRow && selectRow.id) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function addItem() {
  const ids = tableInfo.value.data.map((item) => item.id)
  selectPatrolItemInfo.value.query.queryMap.id.value = ids.toString()
  selectPatrolItemInfo.value.visible = true
}
function selectPatrolItemCallBack(rows = []) {
  if (rows.length) {
    rows.map((row) => {
      return {
        ...row,
      }
    })
    tableInfo.value.data = rows.concat(tableInfo.value.data)
  }
}
function selectPatrolRouteCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.value.data['patrolRouteId'] = data.id
    formInfo.value.data['patrolRouteName'] = data.routeName
  } else {
    formInfo.value.data['patrolRouteId'] = ''
    formInfo.value.data['patrolRouteName'] = ''
  }
}
function callbackAsset(data = undefined) {
  if (data && data.id) {
    formInfo.value.data['assetId'] = data.id
    formInfo.value.data['assetName'] = data.assetName
    formInfo.value.data['assetCode'] = data.assetCode
    formInfo.value.data['location'] = data.location
    disableFieldListItem(true, 'location')
  } else {
    formInfo.value.data['assetId'] = ''
    formInfo.value.data['assetName'] = ''
    formInfo.value.data['assetCode'] = ''
    formInfo.value.data['location'] = ''
    disableFieldListItem(false, 'location')
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function showFieldListItem(show, nameValue) {
  let fieldListClone = proxy.$fn.deepClone(formInfo.value.fieldList)
  fieldListClone.map((item) => {
    if (item.value === nameValue) {
      item.show = show
    }
  })
  formInfo.value.fieldList = fieldListClone
}
function disableFieldListItem(disabled, nameValue) {
  let fieldListClone = proxy.$fn.deepClone(formInfo.value.fieldList)
  fieldListClone.map((item) => {
    if (item.value === nameValue) {
      item.disabled = disabled
    }
  })
  formInfo.value.fieldList = fieldListClone
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let api
      const patrolItemIds = tableInfo.value.data.map((item) => item.id)
      let params = {
        ...formInfo.value.data,
        patrolItemIds: patrolItemIds,
      }
      const type = props.type
      if (type === 'create') {
        api = createPatrolArea
      } else if (type === 'update') {
        api = updatePatrolArea
      } else {
        return
      }
      proxy.$handleAPI(type, api, params).then((res) => {
        if (res.success) {
          showDialog.value = false
          emits('returnBack', true)
        }
      })
    }
  })
}
function getMain() {
  getPatrolAreaById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      const patrolItemIds = resp.data.patrolItemIds
      if (patrolItemIds) {
        const patrolItemId = patrolItemIds.join(',')
        filterInfo.value.query.queryMap.id.value = patrolItemId.toString()
        getList()
      }
      if (resp.data.assetName) {
        disableFieldListItem(true, 'location')
      }
    }
  })
}
function getList() {
  getPatrolItemCustomizeListPage(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
function getCustomize() {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'repairSettingsPatrolItemForAreaDetail-com.slip.spd.entity.vo.core.CorePatrolItemVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      filterInfo.value.query.customizeUserVO = data
      if (props.id) {
        getMain()
      }
    }
  })
}
</script>

<style scoped lang="scss">
.flex {
  display: flex;
  flex: 1;
}

.flex-select :deep(.el-input--small) .el-input__inner {
  height: 28px !important;
}
:deep(.el-form-item__content) {
  display: flex;
}
</style>
